<template>
  <div>
    <my-form-drawer
      :title="title"
      :width="500"
      :visible="visible"
      :layout="layout"
      @ok="save"
      @cancel="onClose"
    >
      <a-tree
        v-model="checkedKeys"
        checkable
        defaultExpandAll
        :show-line="showLine"
        :auto-expand-parent="true"
        :tree-data="treeData"
        :replaceFields="replaceFields"
        @check="onCheck"
      />
    </my-form-drawer>
  </div>
</template>

<script>
import { getAllAuth, getAuth, saveAuth } from "@/services/role";
import MyFormDrawer from "@/components/drawer/MyFormDrawer";

export default {
  name: "roleAssignTree",
  components: { MyFormDrawer },
  props: {
    visible: {
      type: Boolean,
      required: false,
      default: false
    },
    info: {
      type: Object
    }
  },
  data() {
    return {
      title: "角色分配",
      layout: "vertical",
      id: "0",
      showLine: true,
      checkedKeys: [],
      changeKeys: [],
      treeData: [],
      allCheckedKeys: [],
      replaceFields: {
        title: "name",
        key: "id",
        children: "children"
      }
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.getAuth({ id: this.info.id });
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      getAllAuth().then(res => {
        if (res.data.code == 0) {
          this.treeData = res.data.data;
        }
      });
    },

    getAuth(params) {
      getAuth(params).then(res => {
        if (res.data.code == 0) {
          this.checkedKeys = this.showCheckedKey(this.treeData, res.data.data);
        }
      });
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
    },
    onClose() {
      this.$emit("closeAssignForm", false);
    },
    save() {
      this.changeKeys = [...this.checkedKeys];
      let Key = this.changeCheckedKey(this.treeData, this.changeKeys);
      saveAuth({ roleId: this.info.id, resourceIds: Key }).then(res => {
        if (res.data.code == 0) {
          console.log(res);
          this.$message.success("角色分配成功");
          this.onClose();
        }
      });
    },
    changeCheckedKey(treeArr, keyArr) {
      let changArr = keyArr;
      treeArr.forEach(item => {
        if (item.children) {
          this.changeCheckedKey(item.children, changArr);
        }
        if (keyArr.includes(item.id)) {
          changArr.push(item.pid);
        }
      });
      return [...new Set(changArr)];
    },
    showCheckedKey(treeArr, keyArr) {
      let changArr = keyArr;
      treeArr.forEach(item => {
        if (keyArr.includes(item.id)) {
          if (item.children) {
            changArr.splice(
              changArr.findIndex(el => el == item.id),
              1
            );
            this.showCheckedKey(item.children, changArr);
          }
        }
      });
      return [...new Set(changArr)];
    }
  }
};
</script>

<style scoped></style>
